import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import vuexPersist from "vuex-persist";

export default new Vuex.Store({
  state: {
    name: "",
    shoplist: [],
    collist: [],
  },
  mutations: {
    setuser(state, val) {
      state.name = val;
    },
    exit(state) {
      state.name = "";
    },
    // 添加购物车
    add(state, val) {
      var flag = false;
      state.shoplist.forEach((res) => {
        console.log(val);
        console.log(res);
        if (val.product_id == res.product_id) {
          res.num++;
          flag = true;
        }
      });
      if (flag == false) {
        Vue.set(val, "num", 1);
        state.shoplist.push(val);
      }
    },
    // 添加至收藏
    addcoll(state, val) {
      var flag = false;
      state.collist.forEach((res) => {
        if (val.product_id == res.product_id) {
          alert("收藏中已存在");
          flag = true;
        }
      });
      if (flag == false) {
        alert("已添加至收藏");
        // Vue.set(val, "num", 1);
        state.collist.push(val);
      }
    },
    //步进器
    change() {},
    // 删除
    sc(state, val) {
      state.shoplist.splice(val, 1);
    },
    out(state, val) {
      state.collist.splice(val, 1);
    },
  },
  actions: {},
  modules: {},
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
});
